﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web.Mvc;
using Peak.ApplicationServices;
using Peak.ApplicationServices.Services;
using Peak.Core;
using Peak.Core.DataInterfaces;
using MvcContrib;
using Peak.Web.Controllers.Services;
using SharpArch.Core.PersistenceSupport;
using SharpArch.Web.NHibernate;

namespace Peak.Web.Controllers
{
  public class ImportController : BaseController
  {
    private readonly IStoryService _storyService;
    
    public ImportController(ISessionService sessionService, IStoryService storyService)
      : base(sessionService)
    {
      _storyService = storyService;    
    }

    public ActionResult Index()
    {
      return View();
    }

    [Transaction]
    public ActionResult Import()
    {
      if (HttpContext.Request.Files.Count == 0)
        return this.RedirectToAction<ProjectBacklogController>(f=>f.Index(null));

      StoriesCSVReader reader = new StoriesCSVReader(Thread.CurrentPrincipal.Identity.Name);
      StreamReader sr = new StreamReader(HttpContext.Request.Files[0].InputStream);
      IEnumerable<Story> stories = reader.Import(sr);
      sr.Close();

      Project p = _sessionService.Project;
      foreach (Story story in stories)
      {       
        p.AddStory(story);
      }
      
      return this.RedirectToAction<ProjectBacklogController>(f=>f.Index(null));
    }
  }
}
